from math import sqrt
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR

# 导入数据
data = pd.read_excel("E:/spss/data.xlsx", sheet_name='Sheet1')

# 特征和目标变量
X = data.iloc[:, :-1].values  # 所有行，除了最后一列的所有列
Y = data.iloc[:, -1].values  # 所有行，最后一列

# 划分训练集和测试集
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, train_size=0.85, random_state=123)

# 数据标准化
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

# 创建并训练支持向量机回归模型
modelSVR = SVR(kernel='linear')
modelSVR.fit(X_train, Y_train)

#预测
Y_pred=modelSVR.predict(X_test)

# 获取支持向量机回归模型的系数
coefficients = modelSVR.coef_[0]
intercept = modelSVR.intercept_[0]

# 将系数与特征名对应起来
feature_names = data.columns[:-1]
coefficients_df = pd.DataFrame({'Feature': feature_names, 'Coefficient': coefficients})

# 定义一个函数，用于将字体大小应用于Coefficient列
def highlight_coefficient(s):
    return ['font-size: 14px' if val == 'Coefficient' else '' for val in s.index]

# 应用样式
coefficients_df.style.apply(highlight_coefficient, axis=1)

# 打印系数分析结果
print("Support Vector Regression Coefficients:")
print(coefficients_df)

# 绘制系数条形图
plt.figure(figsize=(10, 6))
sns.barplot(x='Coefficient', y='Feature', data=coefficients_df, palette='coolwarm')
plt.title('Coefficients Analysis')
plt.xlabel('Coefficient Value')
plt.ylabel('Feature')
plt.show()
